package cn.schoolwow.util.test.module.replaceFile.parent.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.resource.QueryResource;
import cn.schoolwow.util.domain.replace.ReplaceFile;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Assert;

import java.io.File;
import java.io.IOException;

public class NormalStringReplaceFileProcessFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        copyFile(flowContext);
        replaceFile(flowContext);
    }

    @Override
    public String name() {
        return "正常字符串替换文件测试流程";
    }

    private void copyFile(FlowContext flowContext) throws IOException {
        File tempFile = File.createTempFile("replaceFile", "user.json.copy");
        String filePath = tempFile.getAbsolutePath();
        QueryResource.newQuery("正常替换文件", "module/replaceFile/user.json")
                .execute()
                .copyToFile(filePath);
        File file = new File(filePath);
        flowContext.putCurrentFlowData("file", file);
    }

    private void replaceFile(FlowContext flowContext){
        File file = (File) flowContext.checkData("file");

        ReplaceFile.queryFile(file)
                .addReplaceString("zhangsan", "lisi")
                .addReplaceString("123456", "654321")
                .replaceFile();

        JSONArray array = QueryResource.newQuery("用户文件", file.getAbsolutePath())
                .execute()
                .getAsJSONArray();
        Assert.assertEquals(1, array.size());
        JSONObject user = array.getJSONObject(0);
        Assert.assertEquals(user.getString("username"), "lisi");
        Assert.assertEquals(user.getString("password"), "654321");
    }
}
